import Player     from './player/index'
import DataBus    from './databus'
import Person from './npc/people'
import BackGround from './runtime/background'
import { genByRatio } from './libs/utils'
let ctx = canvas.getContext('2d')
let databus = new DataBus()
let grid
const gridConfig = databus.gridConfig

export default class Main {
    constructor() {
        this.restart()
       
    }

    gridGenerate() {
        let x = gridConfig.row     
        while(x--){
            let  y = gridConfig.column
            while(y--){
                grid[`${x}${y}`] = {
                    occupied: false,
                    x: x*gridConfig.unitW,
                    y: gridConfig.top + y*gridConfig.unitH
                }
            }
          }
    }

    personGenerate() {
        if(databus.frame > 3) return
        // if(databus.frame % databus.frequency) return

        // 寻找出现位置 最多不超过五次
        const genPos = (triedTime = 0) => {
            const row = Math.round(Math.random() *(gridConfig.row - 1))
            const column = Math.round(Math.random() *(gridConfig.column - 1))
            const pos = row + '' + column
            if(!grid[pos].occupied) return pos
            else return triedTime > 5 ? false : genPos(triedTime++)
        }
        const pos = genPos()
        // 没有空位 直接返回
        if(!pos) return
        
        // 新建person实例
        let person = databus.pool.getItemByClass('person', Person)
        grid[pos].occupied = person
        const speed = Math.round(Math.random() * 10) + 10
        const pause = Math.round(Math.random() * 100)
        const type = Number(genByRatio(.3))
        person.init(pos, grid[pos].x, grid[pos].y, type, speed, pause)
        databus.people.push(person)
    }

    restart() {
        databus.reset()
        grid = databus.grid

        this.player = new Player()
        this.bg = new BackGround(ctx)
        this.gridGenerate()
        grid = databus.grid

        window.requestAnimationFrame(
            this.loop.bind(this),
            canvas
        )
    }

    render() {
        ctx.clearRect(0, 0, canvas.width, canvas.height)
        
        this.bg.render(ctx)
        databus.people.forEach(item => item.drawToCanvas(ctx))
    }

    update() {
        databus.people.forEach(item => item.update(ctx))
        this.personGenerate()
    }

    loop() {
        databus.frame++
        // 更新人物出现频率
        if(databus.frame === 1000) databus.frequency = 50
        this.update()
        this.render()
        // window.requestAnimationFrame(
        //     this.loop.bind(this),
        //     canvas
        // )
    }
}